package com.geoai.uimap.api

import android.content.Context
import android.os.Bundle
import com.amap.api.maps.TextureMapView
import com.geoai.uimap.config.MapProvider
import com.geoai.uimap.core.amap.GDMap
import com.geoai.uimap.core.mapbox.MapboxImpl
import com.geoai.uimap.core.osmdroid.OsmMap
import com.geoai.uimap.utils.GEOMapCacheUtils
import com.mapbox.mapboxsdk.maps.MapView


class GEOMapManagerImpl : IGEOMapManager {
    private var geoMap: IGEOMap? = null
    override fun init(context: Context, mapProvider: MapProvider, bundle: Bundle?, mapType: Int) {
        when (mapProvider) {
            MapProvider.GD_MAP -> {
                geoMap = GDMap(context)
                geoMap?.onCreate(bundle, mapType)
            }
            MapProvider.OSM_MAP -> {
                geoMap = OsmMap(context)
                geoMap?.onCreate(bundle, mapType)
            }
            MapProvider.MAP_BOX -> {
                geoMap = MapboxImpl(context)
                geoMap?.onCreate(bundle, mapType)
            }
        }
    }

    override fun onSaveInstanceState(outState: Bundle?) {
        getMap()?.let {
            if (it is GDMap && it.getMapView() is TextureMapView) {
                (it.getMapView() as TextureMapView).onSaveInstanceState(outState)
            } else if (it is MapboxImpl && it.getMapView() is MapView && outState != null) {
                (it.getMapView() as MapView).onSaveInstanceState(outState)
            }
        }
    }

    override fun onResume() {
        getMap()?.onResume()
    }

    override fun onPause() {
        getMap()?.onPause()
    }

    override fun onStart() {
        getMap()?.onStart()
    }

    override fun onStop() {
        getMap()?.onStop()
    }

    override fun onDestroy() {
        getMap()?.onDestroy()
        GEOMapCacheUtils.destroyCache()
        geoMap = null
    }

    override fun getMap(): IGEOMap? {
        return geoMap
    }
}